package xin.yangshuai.csrf01.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * IndexController
 *
 * @author shuai
 * @date 2021/9/14
 */
@Controller
public class IndexController {

    private static String USERNAME = "zhangsan";
    private static String PASSWORD = "123456";

    @RequestMapping("index")
    public String index() {
        return "login";
    }

    @RequestMapping("login")
    public String login(String username, String password, ModelMap modelMap, HttpServletRequest request) {
        if (USERNAME.equals(username) && PASSWORD.equals(password)) {
            request.getSession().setAttribute("user", username + password);
            modelMap.put("message", "success");
        } else {
            modelMap.put("message", "error");
        }
        return "message";
    }

    @RequestMapping("logout")
    public String logout(ModelMap modelMap, HttpServletRequest request) {
        request.getSession().invalidate();
        modelMap.put("message", "logout");
        return "message";
    }

    @RequestMapping("update")
    @ResponseBody
    public Object update(String username, String password, HttpServletRequest request) {
        String user = (String) request.getSession().getAttribute("user");
        Map<String, String> map = new HashMap<>();
        if (user != null) {
            USERNAME = username;
            PASSWORD = password;
            map.put("code", "0");
        } else {
            map.put("code", "-1");
        }
        return map;
    }
}
